package com.example.webapp.hibernate;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.stereotype.Service;

import com.example.webapp.hibernate.user.User;

@Service
public class HibernateManager {
	private SessionFactory sessionFactory;
	
	public HibernateManager() throws NoSuchAlgorithmException {
		sessionFactory = new Configuration().configure().buildSessionFactory();
		
		Session session = createSession();
		Transaction t = session.beginTransaction();
		
		if (session.get(User.class, "admin") == null) {
			User user = new User();
			user.setUsername("admin");
			user.setEmail("robert.krantz@gmail.com");
			
			MessageDigest messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.update("admin".getBytes(), 0, "admin".length());
			String hashedPass = new BigInteger(1,messageDigest.digest()).toString(16);
			user.setPassword(hashedPass);
			
			user.setRoles("ROLE_ADMIN");
			user.setSignupDate(Calendar.getInstance());
			session.save(user);
		}
		
		session.flush();
		t.commit();
		session.close();
	}
	
	public Session createSession() {
		return sessionFactory.openSession();
	}
	
	public void save(Session session, Transaction transaction) {
		session.flush();
		transaction.commit();
	}
	
	@Override
	protected void finalize() throws Throwable {
		sessionFactory.getCurrentSession().close();
		super.finalize();
	}
}
